<?php

namespace app\common\model;

use app\common\model\Common as CommonModel;
use think\facade\Db;
/**
 * 后台用户管理model类
 * @package Home\Model
 */
class SystemMenu extends CommonModel
{
    protected $name = 'System_menu';


    /**
     * 根据传过来的数组，构建以pid为父节点的菜单树..
     * @param $list 构建树所需要的节点，此值是根据权限节点算出来的
     * @param $parent_menu_id   构建树的根节点
     * @return array
     */
    /*public function createTree($list,$pid)
    {
        $data = [];
        foreach($list as $k => $v){
            if($v['pid'] == $pid){
                $row = $v;
                //取当前节点的url
//                $row['url'] = $this->getUrl($v['id']);
                $row['children'] = $this->createTree($list,$v['id']);
                $data[] = $row;
            }
        }

        return $data;
    }*/
    //树形无限极结构
    public function menulist($menu,$id=0,$level=0){
        static $menus = array();
        foreach ($menu as $value) {
            if ($value['pid']==$id) {
                $value['level'] = $level+1;
                if($level == 0)
                {
                    $value['str'] = '';
                }
                elseif($level == 2)
                {
                    $value['str'] = '&emsp;&emsp;&emsp;&emsp;'.'└ ';
                }
                elseif($level == 3)
                {
                    $value['str'] = '&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;'.'└ ';
                }
                else
                {
                    $value['str'] = '&emsp;&emsp;'.'└ ';
                }
                $menus[] = $value;
                $this->menulist($menu,$value['id'],$value['level']);
            }
        }
        return $menus;
    }

    //获取角色的节点的信息
    public function getActList(){

        $admin = new Admin();
        $act_list = $admin -> alias('a')
            ->join('admin_role ar', 'a.role_id=ar.role_id')
            ->where('a.admin_id','=',session('admin_id'))
            ->field('ar.act_list')
            ->find();

        return $act_list['act_list'];
    }


    //无限极结构（顶部栏的数据）
    public function leftMenuList($pid=0,$all_menu_res){
        //获取用户的角色拥有的节点权限
        $act_list = $this->getActList();

        $menu_res = $this->where('pid','=',$pid)->where('show','=',1)->order('sort asc')->select();
        static $menuInfo = [];
        foreach($menu_res as $k=>$v){
            if(session('admin_id') == 1){
                $new_arr['title'] = $v['name'];
                $new_arr['icon'] = 'fa ' . $v['icon'];
                $new_arr['href'] = $v['href'];
                $new_arr['target'] = '_self';
                $ids = $this->getAllChilds($all_menu_res, $v['id']);
                if (count($ids) > 0) {
                    $new_arr['child'] = $this->leftMenuListChild($v['id'], $all_menu_res, $act_list);
                }
                array_push($menuInfo, $new_arr);
            }else {
                if (in_array($v['id'], explode(',', $act_list))) {
                    $new_arr['title'] = $v['name'];
                    $new_arr['icon'] = 'fa ' . $v['icon'];
                    $new_arr['href'] = $v['href'];
                    $new_arr['target'] = '_self';
                    $ids = $this->getAllChilds($all_menu_res, $v['id']);
                    if (count($ids) > 0) {
                        $new_arr['child'] = $this->leftMenuListChild($v['id'], $all_menu_res, $act_list);
                    }
                    array_push($menuInfo, $new_arr);
                }
            }
        }
        return $menuInfo;
    }

    //无限极结构（左侧栏子集的数据 ）
    public function leftMenuListChild($pid,$all_menu_res,$act_list){

        $menu_res = $this->where('pid','=',$pid)->where("show","=",1)->order('sort asc')->select();
        $menuInfo = [];
        foreach($menu_res as $k=>$v){

            if(session('admin_id') == 1){
                $new_arr['title'] = $v['name'];
                $new_arr['icon'] = 'fa ' . $v['icon'];
                $new_arr['href'] = $v['href'];
                $new_arr['target'] = '_self';
                $ids = $this->getAllChilds($all_menu_res, $v['id']);
                if (count($ids) > 0) {
                    $new_arr['child'] = $this->leftMenuListChild($v['id'], $all_menu_res, $act_list);
                }
                array_push($menuInfo, $new_arr);
            }else {
                if (in_array($v['id'], explode(',', $act_list))) {
                    $new_arr['title'] = $v['name'];
                    $new_arr['icon'] = 'fa ' . $v['icon'];
                    $new_arr['href'] = $v['href'];
                    $new_arr['target'] = '_self';
                    $ids = $this->getAllChilds($all_menu_res, $v['id']);
                    if (count($ids) > 0) {
                        $new_arr['child'] = $this->leftMenuListChild($v['id'], $all_menu_res, $act_list);
                    }
                    array_push($menuInfo, $new_arr);
                }
            }
        }
        return $menuInfo;
    }

    //获取它的所有下级
    public function getAllChilds($data, $pid , $is_first_time = true)
    {
        static $arr = [];
        if ($is_first_time) {
            $arr = [];
        }
        foreach ($data as $key => $val) {
            if ($val['pid'] == $pid) {
                $arr[] = $val['id'];
                $this->getAllChilds($data, $val['id'], false);
            }
        }
        return $arr;
    }

    //添加和修改操作
    public function handle($param){
        $act = $param['act'];

        $result = [
            'code' => 0,
            'msg'    => '',
            'data'   => [],
        ];

        $data['pid'] = $param['pid'];
        $data['name'] = $param['name'];
        $data['href'] = $param['href'];
        $data['icon'] = $param['icon'];
        $data['sort'] = $param['sort'];
        $data['show'] = $param['show'];
        $right = '';
        if(!empty($param['href'])){
            $href_arr = explode('/',$param['href']);
            if(count($href_arr) < 3 ){
                $result['msg'] = '节点跳转的格式错误';
                return $result;
            }
        }

        if(!empty($param['right'])){
            $right = implode(',',$param['right']);
        }
        $data['right'] = $right;


        if($act == 'add'){
            $data['add_time'] = time();
            $r = $this->insertGetId($data);
            $id = $r;
            $ty = '添加';
        }else{
            $data['update_time'] = time();
            $r = $this->where('id','=',$param['id'])->update($data);
            $id = $param['id'];
            $ty = '修改';
        }

        if(!$r){
            $result['msg'] = '操作失败';
            return $result;
        }

        adminLog($param['name']."节点".$ty,$id);
        $result['code'] = 1;
        $result['msg'] = '操作成功';
        return $result;
    }


    // index页面数据获取
    /*public function tableData($post,$field='*',$isPage = true)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = 20;
        }

        $tableWhere = $this->tableWhere($post);
        $query      = $this
            ->field($field)
            ->where($tableWhere['where'])->whereOr($tableWhere['whereOr'])->order($tableWhere['order']);


        if ($isPage) {
            $list        = $query->paginate($limit);
            $data        = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $re['count'] = $list->total();
        } else {
            $list        = $query->select();
            $data        = $this->tableFormat($list);         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $re['count'] = count($list);
        }

        $re['code'] = 1;
        $re['msg']  = '';
        $re['data'] = $data;
        return $re;
    }


    protected function tableWhere($post)
    {
        $where = $whereOr = [];

        $result['where']   = $where;
        $result['whereOr'] = $whereOr;

        $result['field'] = "*";
        $pk = $this->pk;
        $result['order'] = [$pk => 'desc'];
        return $result;
    }

    protected function tableFormat($list)
    {

        return $list;
    }*/





}